<template>
  <div class="">
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 第一列 -->
        <el-col :span="8">
          <!-- 搜索与添加 -->
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.username"
            clearable @clear="getUserList">
            <template #append>
              <span class="iconfont">&#xe601;</span>
              <el-button @click="getUserList"></el-button>
            </template>
          </el-input>
        </el-col>
        <!-- 第二列 -->
        <el-col :span="4">
          <el-button type="primary" @click="changeAdDialogVisible">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="vip" prop="vip"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <!-- eslint-disable-next-line vue/valid-v-model -->
            <el-switch v-model="scope.row.status" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="createTime" width="150px"></el-table-column>
        <el-table-column label="操作" width="200px">
          <!-- 这样可以获取到这一行的数据 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="iconfont icon-blogxiugai" size="mini"
                @click="showEditDialog(scope.row.userId)">
              </el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip class=" item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="iconfont icon-blogshanchu" size="mini"
                @click="removeUserById(scope.row.userId)"></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="权限管理" placement="top"
              :enterable="false">
              <el-button type="warning" icon="iconfont icon-blogquanxianfenpei" size="mini">
              </el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <!-- eslint-disable-next-line vue/valid-v-model -->
      <el-pagination v-model:currentPage="queryInfo.numPage" :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.numSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>

      <!-- 添加用户的对话框 -->
      <el-dialog :visible.sync="addDialogVisible" title="添加用户" width="50%" :append-to-body="true"
        @close="addDialogClosed">

        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px"
          class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>

        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改用户的对话框 -->
      <el-dialog :visible.sync="editDialogVisible" title="修改用户" width="50%" :append-to-body="true"
        @close="editDialogClosed">

        <!-- 内容主体区域 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px"
          class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="phone" prop="phone">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="editUserInfo">确定</el-button>
          </span>
        </template>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: '',
  data () {
    // 校验邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // eslint-disable-next-line no-unused-vars
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 校验手机号的规则
    var checkPhone = (rule, value, cb) => {
      // eslint-disable-next-line no-unused-vars
      const regPhone = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (regPhone.test(value)) {
        // 合法的手机号
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        username: null,
        numPage: 1,
        numSize: 4
      },
      userList: [],
      total: 0,
      updateUserStatus: {
        userId: 15,
        status: true
      },
      // 控制添加用户的对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '用户名的长度在6~12个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    getUserList () {
      this.$http({
        methods: 'GET',
        url: 'api/admin/user/getUsers',
        params: this.queryInfo,
        headers: {
          token: window.sessionStorage.getItem('token')
        }
      }).then((res) => {
        console.log(res.data)
        console.log(this.queryInfo.username)
        this.userList = res.data.list
        this.total = res.data.total
        this.$message.success('请求成功')
      }).catch((res) => {
        this.$message.error('获取用户列表失败')
      })
    },
    // 监听pageSize事件
    handleSizeChange (newSize) {
      this.queryInfo.numSize = newSize
      this.getUserList()
    },
    // 监听页码值改变
    handleCurrentChange (newPage) {
      this.queryInfo.numPage = newPage
      this.getUserList()
    },
    // 监听开关
    userStateChanged (userInfo) {
      this.updateUserStatus.status = userInfo.status
      this.updateUserStatus.userId = userInfo.userId
      console.log(userInfo)
      // eslint-disable-next-line no-unused-vars
      const data = this.$http.post('api/admin/user/updateUserStatus',
        JSON.stringify(this.updateUserStatus), { headers: { token: window.sessionStorage.getItem('token') } })
    },
    changeAdDialogVisible () {
      this.addDialogVisible = true
      console.log(this.addDialogVisible)
    },
    // 监听添加用户对话框
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新用户
    addUser () {
      this.$refs.addFormRef.validate(valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 可以发起添加用户的请求
      })
    },
    // 展示编辑用户的对话框
    showEditDialog (id) {
      // 通过id请求
      this.$http.get('api/admin/user/getUserById', {
        params: {
          id: id
        },
        headers: {
          token: window.sessionStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code !== 200) return this.$message.error(res.data.msg)
        this.editForm = res.data.list
        console.log(this.editForm)
      })

      this.editDialogVisible = true
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo () {
      this.$refs.editFormRef.validate(valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // console.log(valid)
        // 可以发起添加用户的请求
        this.$http.post('api/admin/user/updateUser', this.editForm, { headers: { token: window.sessionStorage.getItem('token') } }).then(res => {
          this.editDialogVisible = false
          this.getUserList()
          return this.$message.success('修改成功！')
        }).catch(res => {
          if (res.data.code === 500) {
            this.message.error(res.data.msg)
          }
        })
      })
    },
    // 根据id删除对应的信息
    async removeUserById (id) {
      // 提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确定，返回confirm
      // 如果用户取消，则返回的是cancel

      if (confirmResult !== 'confirm') {
        this.$message.info('已取消删除')
      }
      // 确认删除，可以发动请求
      var deleteData = JSON.stringify({
        id: id
      })
      this.$http.post('api/admin/user/deleteUserById', deleteData, { headers: { token: window.sessionStorage.getItem('token') } })
        .then(res => {
          this.$message.success(res.data.msg)
          this.getUserList()
        }).catch(res => {
          this.$message.error('删除失败，请稍后重试或联系管理员')
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
